今天又双叒繼續primereact 的DataTable
來說點關於 Edit
直接上全Code
其實就拉官網,
比較值得注意的是如果有寫TS的
const [products, setProducts] = useState<Product[]>();
這裡是建議寫成
const [products, setProducts] = useState<Product[]>([]);
加個空陣列預設,
因此在做onRowEditComplete時才不會報undefined的錯
import React, { useEffect, useState } from 'react';
import { DataTable, DataTableRowEditCompleteEvent } from 'primereact/datatable';
import { Column, ColumnEditorOptions } from 'primereact/column';
import { InputText } from 'primereact/inputtext';
import { InputNumber, InputNumberValueChangeEvent } from 'primereact/inputnumber';
import { Dropdown, DropdownChangeEvent } from 'primereact/dropdown';
import { ProductService } from '../service/table';
import { Product } from '../interfaces/table';
const Tables9Compnent: React.FC = () => {
const [tabledata, setTabledata] = useState<Product[]>([]);
const [statuses] = useState<string[]>(['INSTOCK', 'LOWSTOCK', 'OUTOFSTOCK']);
let service = new ProductService();
useEffect(() => {
service.getProductsMini().then(data => setTabledata(data));
}, []);
const onRowEditComplete = (e: DataTableRowEditCompleteEvent) => {
let _products = [...tabledata];
let { newData, index } = e;
_products[index] = newData as Product;
setTabledata(_products);
};
const textEditor = (options: ColumnEditorOptions) => {
return <InputText type="text" value={options.value} onChange={(e: React.ChangeEvent<HTMLInputElement>) => options.editorCallback!(e.target.value)} />;
};
const statusEditor = (options: ColumnEditorOptions) => {
return (
<Dropdown
value={options.value}
options={statuses}
onChange={(e: DropdownChangeEvent) => options.editorCallback!(e.value)}
placeholder="Select a Status"
itemTemplate={(option) => {
return <div>{option}</div>;
}}
/>
);
};
const priceEditor = (options: ColumnEditorOptions) => {
return <InputNumber value={options.value} onValueChange={(e: InputNumberValueChangeEvent) => options.editorCallback!(e.value)} mode="currency" currency="TWD" locale="zh-cn" />;
};
const priceBodyTemplate = (rowData: Product) => {
return new Intl.NumberFormat('zh-cn', { style: 'currency', currency: 'TWD' }).format(rowData.price);
};
const allowEdit = (rowData: Product) => {
return rowData.name !== 'Blue Band';
};
return (
<div>
<DataTable value={tabledata} editMode="row" dataKey="id" onRowEditComplete={onRowEditComplete}>
<Column field="code" header="商品編號" editor={(options) => textEditor(options)} />
<Column field="name" header="商品名稱" editor={(options) => textEditor(options)} />
<Column field="inventoryStatus" header="庫存狀況" editor={(options) => statusEditor(options)} />
<Column field="price" header="價格" body={priceBodyTemplate} editor={(options) => priceEditor(options)} />
<Column rowEditor={allowEdit} bodyStyle={{ textAlign: 'center' }} />
</DataTable>
</div>
);
}
export default Tables9Compnent;
editMode 設定編輯的模式 cell(單格) | row (一列)
利用column 的 editor api 呼叫 editorCallback 儲存newData
最後用onRowEditComplete紀錄
好了 今天就到這裡
明天見